package com.wyp168.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wyp168.gulimall.product.dao.CategoryBrandRelationDao;
import com.wyp168.gulimall.product.vo.Category2VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyp168.common.utils.PageUtils;
import com.wyp168.common.utils.Query;

import com.wyp168.gulimall.product.dao.CategoryDao;
import com.wyp168.gulimall.product.entity.CategoryEntity;
import com.wyp168.gulimall.product.service.CategoryService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //获取所有的商品菜单信息
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> entities = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0L)
                .map(categoryEntity -> {
                    //TODO 构建子菜单
                    categoryEntity.setChildren(buildChildren(categoryEntity.getCatId(), categoryEntities));
                    return categoryEntity;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        return entities;
    }

    @Override
    public boolean removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单，是否被别的地方引用
//        asList.removeIf(id -> (baseMapper.selectById(id).getCatLevel() < 3) && (baseMapper.selectCount(new QueryWrapper<CategoryEntity>().eq("parent_cid", id)) > 0));
        int count = baseMapper.deleteBatchIds(asList);
        return count > 0;
    }

    public List<CategoryEntity> buildChildren(Long parentId, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> children = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == parentId)
                .map(categoryEntity -> {
                    //TODO 构建子菜单
                    categoryEntity.setChildren(buildChildren(categoryEntity.getCatId(), categoryEntities));
                    return categoryEntity;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        return children;
    }

    @Override
    public boolean saveIfLevelLowerTree(CategoryEntity category) {
        if (category.getCatLevel() > 3) {
            return false;
        }
        int insert = baseMapper.insert(category);
        return insert > 0;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        paths = findParentPath(catelogId, paths);
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationDao.updateCategory(category.getCatId(), category.getName());
        }
    }

    @Override
    public List<CategoryEntity> getLevelOneCategorys() {
        return baseMapper.selectList(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getParentCid, 0));
    }

    @Override
    public Map<String, List<Category2VO>> getCategoryJson() {
        //1.查出所有一级分类
        List<CategoryEntity> levelOneCategorys = this.getLevelOneCategorys();
        //封装数据
        Map<String, List<Category2VO>> result = levelOneCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), categoryEntity -> {
            //根据这个一级分类查询二级分类
            List<CategoryEntity> twoCategoryList = baseMapper.selectList(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getParentCid, categoryEntity.getCatId()));
            List<Category2VO> category2VOList = new ArrayList<>();
            //封装数据
            if (!CollectionUtils.isEmpty(twoCategoryList)) {
                category2VOList = twoCategoryList.stream().map(item -> {
                    Category2VO category2VO = new Category2VO(categoryEntity.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //根据二级分类，找三级分类，然后封装成List，并放到category2VO中
                    List<CategoryEntity> threeCategoryList = baseMapper.selectList(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getParentCid, item.getCatId()));
                    if (!CollectionUtils.isEmpty(threeCategoryList)) {
                        List<Category2VO.Category3VO> category3VOS = threeCategoryList.stream().map(threeCategory -> {
                            Category2VO.Category3VO category3VO = new Category2VO.Category3VO(item.getCatId().toString(), threeCategory.getCatId().toString(), threeCategory.getName());
                            return category3VO;
                        }).collect(Collectors.toList());
                        category2VO.setCatalog3List(category3VOS);
                    }
                    return category2VO;
                }).collect(Collectors.toList());
            }
            return category2VOList;
        }));
        return result;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        CategoryEntity byId = this.getById(catelogId);
        paths.add(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

}